package org.self.service.impl;

import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.self.service.IJwtService;
import org.springframework.stereotype.Component;
import self.constance.Constance;

import javax.servlet.http.HttpServletRequest;

/**
 * 作者: liYU
 * 项目名称: WX_Self_Iot_parent
 * 标题: JwtService
 * 该类描述: TODO
 * 创建日期: 2025/3/30 0:40
 */
@Component
public class JwtService implements IJwtService {

    @Override
    public Claims getClaimsJwsBody(String token) {
        return Jwts.parser()
                   .setSigningKey(Constance.JWT_SIGN)
                   .parseClaimsJws(token)
                   .getBody();
    }

    @Override
    public String getId(String token) {
        return getClaimsJwsBody(token).getId();
    }

    @Override
    public String getUsername(String token) {
        return getClaimsJwsBody(token).getSubject();
    }

    @Override
    public String getToken(HttpServletRequest req, String keyName) {
        //token有可能被放在了头部信息里
        String token = req.getHeader(keyName);
        if (StrUtil.isEmpty(token)) {
            //token也有可能被放在了参数信息里
            token = req.getParameter(keyName);
        }
        return token;
    }
}
